package mqs

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	GuitarModel "go-weixin/app/guitar/model"
	"go-weixin/app/mqueue/tasks/internal/svc"
	ESModel "go-weixin/common/es/model"

	"github.com/zeromicro/go-zero/core/logx"
)

type ESGuitarKQTask struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewMyKQConsume(ctx context.Context, svcCtx *svc.ServiceContext) *ESGuitarKQTask {
	return &ESGuitarKQTask{
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// 消费者
func (l *ESGuitarKQTask) Consume(key, val string) error {
	logx.Infof("执行异步任务 key:%s , val :%s", key, val)
	guitarModel := ESModel.NewGuitarESModel()
	searchBodyByte := fmt.Sprintf(`{
  "query": {
    "term": {
      "title": "%s"
    }
  }
}`, val)
	data, err := l.svcCtx.Es.SearchByQuery(context.Background(), searchBodyByte, guitarModel.IndexName())
	if err != nil {
		return errors.New("es查询异常")
	}
	if data.Hits.TotalHits.Value == 0 {
		g := new(GuitarModel.GuitarModel)
		_, err := l.svcCtx.ChenDb.Where("title = ?", val).Get(g)
		if err != nil {
			return errors.New("mysql.查询异常")
		}
		guitarModel.Title = val
		guitarModel.GuitarId = g.Id
		insertBodyByte, err := json.Marshal(guitarModel)
		if err != nil {
			return errors.New("guitar.add序列化异常")
		}
		// es插入
		if err = l.svcCtx.Es.Insert(context.Background(), guitarModel.IndexName(), string(insertBodyByte)); err != nil {
			return errors.New("es插入异常")
		}
	}
	return nil
}
